<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <div class="search-box">
        <el-input
          v-model.trim="queryInfo.query"
          placeholder="请输入搜索内容"
          class="search-input"
          clearable
          @input="searchFn"
        ></el-input>
        <button class="el-icon-search" @click="searchBTN"></button>
        <el-button type="primary" @click="addBtn">添加用户</el-button>
        <!-- 添加对话框开始 -->
        <el-dialog
          title="添加用户"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose"
        >
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                type="password"
                show-password
                v-model="ruleForm.password"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="ruleForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addConfirm">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 添加对话框结束 -->
        <!-- 编辑对话框开始 -->
        <el-dialog
          title="修改用户"
          :visible.sync="editVisible"
          width="30%"
          :before-close="handleClose"
        >
          <el-form
            :model="editData"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input disabled v-model="editData.username"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editData.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="editData.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editVisible = false">取 消</el-button>
            <el-button type="primary" @click="editConfirm">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 编辑对话框结束 -->
        <!-- 分配角色对话框开始 -->
        <el-dialog
          title="分配角色"
          :visible.sync="roleDialogVisible"
          width="30%"
          :before-close="handleClose"
        >
          <div class="roleDiv">当前用户：{{ roleData.username }}</div>
          <div class="roleDiv">当前角色：{{ roleData.role_name }}</div>
          <div class="roleDiv">
            <span>分配新角色：</span>
            <el-select
              v-model="optionValue"
              placeholder="请选择"
              @change="optionFn"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="roleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="roleConfirm">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 分配角色对话框结束 -->
      </div>
      <div class="table">
        <el-table
          border
          :data="tableData"
          style="width: 100%"
          :row-class-name="tableRowClassName"
        >
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="username" label="姓名" width="180">
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="180">
          </el-table-column>
          <el-table-column prop="mobile" label="电话"> </el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column prop="mg_state" label="状态">
            <template scope="item">
              <el-switch
                v-model="item.row.mg_state"
                active-color="#409eff"
                inactive-color="#dcdfe6"
                @change="changeStatus(item.row.id, item.row.mg_state)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作" width="180">
            <template scope="item">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="small"
                @click="editFn(item.row.id)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="deleteFn(item.row.id)"
              ></el-button>
              <el-tooltip
                class="tooltip"
                effect="dark"
                content="分配角色"
                placement="top"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="small"
                  @click="roleFn(item.row.id)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页模块 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
// 引入lodash防抖
import { debounce } from 'lodash'
export default {
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      editVisible: false,
      roleDialogVisible: false,
      roleId: '',
      // 分配角色数据
      roleData: {
        id: '',
        username: '',
        role_name: '',
        rid: '',
      },
      // 分页数据
      total: 0,
      // 表单校验
      ruleForm: {
        email: '',
        mobile: '',
        username: '',
        password: '',
      },
      // 添加用户中的表单数据
      formData: {
        email: '',
        mobile: '',
        username: '',
        password: '',
      },
      // 编辑用户中的表单数据
      editData: {
        email: '',
        mobile: '',
        username: '',
        id: '',
      },
      // 查询对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10,
      },
      // 表单校验规则
      rules: {
        // 用户名校验
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 8 个字符', trigger: 'blur' },
        ],
        // 密码校验
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 12,
            message: '长度在 6 到 16 个字符',
            trigger: 'blur',
          },
        ],
        // 手机号校验规则
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: ['blur', 'change'],
          },
        ],
        // 邮箱校验
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱格式',
            trigger: ['blur', 'change'],
          },
        ],
      },
      // 分配角色下拉菜单数据
      options: [],
      optionValue: '',
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 搜索按钮功能模块
    // 使用 Lodash 的 debounce 函数来实现防抖
    searchBTN: debounce(function () {
      // 处理输入事件
      this.getUserList()
      console.log('搜索按钮防抖')
    }, 300),
    // 一个异步请求 获取用户信息  将信息给tableData
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: {
          ...this.queryInfo,
        },
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.tableData = res.data.users
      this.total = res.data.total
    },

    // 表格隔行变色
    tableRowClassName({ rowIndex }) {
      return rowIndex % 2 == 0 ? 'warning-row' : 'success-row'
    },

    //根据 ID 查询⽤户信息接口

    async queryUserInfo(id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.tableData = res.data
      console.log(res)
    },

    // 点击x号关闭弹窗
    handleClose(done) {
      done()
    },

    // 分页模块
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },

    // 使用 Lodash 的 debounce 函数来实现防抖
    // // 添加用户弹窗确定按钮
    addConfirm: debounce(function () {
      // 处理输入事件
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.dialogVisible = false
          this.postUserInfo()
          // 在这里可以执行提交操作，例如发送请求
        } else {
          this.$message.error('请按要求填写完整')
          return false
        }
      })
    }, 300),

    // 提交注册用户请求
    async postUserInfo() {
      const { data: res } = await this.$http.post('users', this.ruleForm)
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
    },

    // 删除请求
    async delUserInfo(id) {
      const { data: res } = await this.$http.delete(`users/${Number(id)}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
    },

    deleteFn(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.delUserInfo(id)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },

    // 添加用户按钮
    addBtn() {
      ;(this.ruleForm = {
        email: '',
        mobile: '',
        username: '',
        password: '',
      }),
        (this.dialogVisible = true)
    },
    // 改变用户状态函数
    changeStatus(id, status) {
      this.putStatus(id, status)
    },
    // 改变用户状态请求
    async putStatus(id, status) {
      const { data: res } = await this.$http.put(
        `users/${Number(id)}/state/${status}`
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },

    // 搜索框的input事件
    // 使用 Lodash 的 debounce 函数来实现防抖
    searchFn: debounce(function () {
      // 处理输入事件
      if (!this.queryInfo.query) {
        this.getUserList()
        console.log('搜索框的input事件防抖')
      }
    }, 300),

    // 查询用户信息
    async getUserInfo(id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      this.editData.id = res.data.id
      this.editData.username = res.data.username
      this.editData.mobile = res.data.mobile
      this.editData.email = res.data.email
    },

    // 编辑功能模块
    editFn(id) {
      this.editVisible = true
      this.getUserInfo(id)
    },

    // 编辑弹窗确定按钮
    // 使用 Lodash 的 debounce 函数来实现防抖
    editConfirm: debounce(function () {
      // 点击确定按钮再次调用validate进行校验
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.editVisible = false
          this.postUserInfo()
          // 在这里可以执行提交操作，例如发送请求
        } else {
          this.$message.error('请按要求填写完整')
          return false
        }
      })
    }, 500),

    // 修改用户信息请求
    async putUserInfo() {
      const { data: res } = await this.$http.put('users/' + this.editData.id, {
        email: this.editData.email,
        mobile: this.editData.mobile,
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
    },

    // 获取roles
    async getRoles() {
      const { data: res } = await this.$http.get(`roles/`)
      this.options = res.data
    },

    // 分配⽤户⻆⾊请求
    async putUserRole(id, rid) {
      const { data: res } = await this.$http.put(`users/${id}/role`, {
        rid,
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
    },
    roleFn(id) {
      // 将select设置为默认值
      this.optionValue = null
      this.roleId = ''
      // 显示分配角色弹窗
      this.roleDialogVisible = true
      // 将点击的这行数据通过id和filter过滤后 将数据放在obj中 然后赋值给roleData
      const obj = this.tableData.filter((item) => item.id == id)[0]
      this.roleData.id = obj.id
      this.roleData.username = obj.username
      this.roleData.role_name = obj.role_name
      this.getRoles()
    },

    roleConfirm() {
      if (this.roleId) {
        this.putUserRole(this.roleData.id, this.roleId)
        this.roleDialogVisible = false
      } else {
        this.roleDialogVisible = false
        this.$message.warning('取消修改')
      }
    },
    optionFn(value) {
      this.roleId = value
    },
  },
}
</script>

<style lang="less" scoped>
.table ::v-deep.el-table .warning-row {
  background: #fff;
}

.table ::v-deep.el-table .success-row {
  background: #fafafa;
}

.search-box {
  display: flex;
  width: 400px;
  align-items: center;
}

.search-input {
  flex: 1;
}
.search-input ::v-deep input {
  border-radius: 4px;
  border-bottom-right-radius: 0;
  border-top-right-radius: 0;
}
.el-icon-search {
  display: block;
  height: 40px;
  background-color: #f5f7fa;
  cursor: pointer;
  padding: 0 20px;
  border: 1px solid #ccc;
  border-left: none;
  color: #a3aeb5;
  margin-right: 10px;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}
.roleDiv {
  margin: 15px 0;
}
</style>
